var config = require('./config.js')
//app.js
App({
  onLaunch: function () {
    const that = this;
    /*****************判断本地是否有登陆缓存************ */
    var openid = that.globalData.openid;
    if (openid == '') { //检查 token 是否存在 如果不存在调用登录
      that.login();
    }
    else {
      that.get_user_info();
    }
    /*****************结束************ */
    // 展示本地存储能力  没啥用 暂时当个例子吧
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

  },
  login: function () {
    // 登录部分代码
    var that = this;
    wx.login({
      success: function (res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          var url = that.globalData.serverBaseAddr + "/apic/getopenid/" + res.code;
          var params = GetSign("code=" + res.code);
          url = url + "?" + params
          wx.request({
            url: url,
            success: function (res2) {
              if (res2.data.code == 0) {
                that.globalData.openid = res2.data.data.openid;
                that.globalData.sessionkey = res2.data.data.session_key;
                //根据openId判断是否
                that.get_user_info()
              }
              else {
                wx.showToast({
                  title: res2.data.msg,
                  icon: 'none'
                })
              }

            }
          })
        }
        else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  get_user_info: function (token) {
    const that = this;
    //获取用户信息
    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        that.globalData.userInfo = res.userInfo
        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况 TODO
        if (that.userInfoReadyCallback) {
          that.userInfoReadyCallback(res)
        }
        //根据openid 判断用户是否注册
        //如果未注册则注册并返回用户信息
        //如果已注册则直接返回用户信息
        var newid = that.newGuid();
        var data = { "type": "", "nickName": res.userInfo.nickName, "avatarUrl": res.userInfo.avatarUrl, "gender": res.userInfo.gender, "country": res.userInfo.country, "province": res.userInfo.city }
        var url2 = that.globalData.serverBaseAddr + "/apip/login";
        var params = "openid=" + that.globalData.openid + "&id=" + newid
        params = GetSign(params);
        url2 = url2 + "?" + params
        wx.request({
          url: url2,
          data: data,
          method: 'post',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.code == 0) {
              const userdata = res.data.data;
              that.globalData.accounttype = userdata.accounttype;
              that.globalData.patientid = userdata.patientId;
              that.globalData.tel = userdata.tel;
              if (userdata.id) {
                that.globalData.accountid = userdata.id;
              }
              else {
                that.globalData.accountid = newid;
              }
            }
            else{
              wx.showToast({
                title: res2.data.msg,
                icon: 'none'
              })
            }
          }
        })

      },
      fail: function () {
        //getUserInfo fail
      },
      complete: function () {
        //getUserInfo complete
      }
    })
  },
  globalData: {
    userInfo: null,//用户信息，包含昵称/头像等相关信息
    tel: '',
    serverBaseAddr: 'https://app1.lzgkyl.top',//后台服务地址
    pagesize: 15,
    // userid:'E316A15A-12DB-46A8-A2FC-9563FC3AC0A8',//作废-改为accountid
    accountid: '',
    accounttype: 0,//账号类型 0，自动注册用户，未绑定患者id /  1，已绑定患者
    patientid: '', //患者id,
    openid: '',
    sessionkey: ''
  },
  S4: function () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  },
  newGuid: function () {
    return (this.S4() + this.S4() + "_" + this.S4() + "_" + this.S4() + "_" + this.S4() + "_" + this.S4() + this.S4() + this.S4());
  }

})


function encodeUTF8(s) {
  var i, r = [], c, x;
  for (i = 0; i < s.length; i++)
    if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
    else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
    else {
      if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
        c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
      else r.push(0xE0 + (c >> 12 & 0xF));
      r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    };
  return r;
};

// 字符串加密成 hex 字符串
function sha1(s) {
  var data = new Uint8Array(encodeUTF8(s))
  var i, j, t;
  var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
  s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
  for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
  s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
  s[l - 1] = data.length << 3;
  var w = [], f = [
    function () { return m[1] & m[2] | ~m[1] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; },
    function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
    function () { return m[1] ^ m[2] ^ m[3]; }
  ], rol = function (n, c) { return n << c | n >>> (32 - c); },
    k = [1518500249, 1859775393, -1894007588, -899497514],
    m = [1732584193, -271733879, null, null, -1009589776];
  m[2] = ~m[0], m[3] = ~m[1];
  for (i = 0; i < s.length; i += 16) {
    var o = m.slice(0);
    for (j = 0; j < 80; j++)
      w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
    for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
  };
  t = new DataView(new Uint32Array(m).buffer);
  for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);

  var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
    return (e < 16 ? "0" : "") + e.toString(16);
  }).join("");

  return hex;
};


function GetSign(parameters) {

  //第一步：索取应用系统私钥key,应用系统私钥key(此值为开发调试临时使用)
  var private_key = "88e02bd6_8d05_8173_90dd_82701f386d23";//

  //第二步：给调用url加上timestamp参数
  var timestamp = (new Date()).valueOf();
  if (parameters == null) {
    parameters = "tamp=" + timestamp;
  }
  else {
    parameters += "&tamp=" + timestamp;
  }


  //第三步：取出url中的所有参数
  //第四步：把字典值，按key的字母顺序排序，并把key统一转成小写
  parameters = parameters.toLowerCase();
  var parArray = parameters.split("&");
  parArray = parArray.sort();
  // 第五步：把排序后的字典中的key和value串到一起
  parArray = parArray.join("");
  parArray = parArray.replace(/=/g, "");

  //第六步：把私钥key值放加到字符串头部
  parArray = private_key + parArray;

  //第七步：对字符串进行SHA1加密，所得结果既为签名值
  var hash = sha1(parArray)
  //第八步：把签名值追加命令url中
  parameters = parameters + "&signature=" + hash.toLowerCase();
  return parameters
}
